<template>
  <div class="rtsp-config">
    <a-card title="RTSP 服务配置" :bordered="false">
      <a-spin :spinning="loading">
        <a-form
          :model="form"
          layout="vertical"
          @finish="onSubmit"
        >
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item label="启用服务" name="enabled">
                <a-switch
                  v-model:checked="form.enabled"
                  :disabled="loading"
                />
              </a-form-item>
              <div class="status-info">
                <span class="status-label">当前状态：</span>
                <a-tag :color="form.enabled ? 'green' : 'default'">
                  {{ form.enabled ? '已启用' : '未启用' }}
                </a-tag>
              </div>
            </a-col>

            <a-col :span="8">
              <a-form-item
                label="监听端口"
                name="port"
                :rules="[
                  { required: true, message: '请输入端口号' },
                  { validator: validatePort }
                ]"
              >
                <a-input-number
                  v-model:value="form.port"
                  :min="1"
                  :max="65535"
                  :disabled="loading"
                  style="width: 100%"
                  placeholder="554"
                />
              </a-form-item>
              <div class="help-text">
                默认端口554，修改后需确保防火墙和客户端同步更新
              </div>
            </a-col>

            <a-col :span="8">
              <a-descriptions size="small" bordered :column="1">
                <a-descriptions-item label="设备地址">
                  {{ deviceIP }}
                </a-descriptions-item>
                <a-descriptions-item label="服务状态">
                  <a-tag :color="form.enabled ? 'processing' : 'default'">
                    {{ form.enabled ? '运行中' : '已停止' }}
                  </a-tag>
                </a-descriptions-item>
              </a-descriptions>
            </a-col>
          </a-row>

          <a-divider />

          <div class="url-examples">
            <h4>RTSP 访问地址示例</h4>
            <p class="description">
              实时流路径：/live/{通道}/{码流}，录制/对讲路径：/record/{通道}
            </p>

            <a-descriptions size="small" :column="1" bordered>
              <a-descriptions-item label="实时预览">
                <a-typography-paragraph
                  :copyable="{ text: liveURL }"
                  class="url-display"
                >
                  {{ liveURL }}
                </a-typography-paragraph>
              </a-descriptions-item>
              <a-descriptions-item label="录制/对讲">
                <a-typography-paragraph
                  :copyable="{ text: recordURL }"
                  class="url-display"
                >
                  {{ recordURL }}
                </a-typography-paragraph>
              </a-descriptions-item>
            </a-descriptions>
          </div>

          <div class="actions">
            <a-space>
              <a-button
                type="primary"
                html-type="submit"
                :loading="loading"
              >
                保存配置
              </a-button>
              <a-button @click="onReset" :disabled="loading">
                重置
              </a-button>
              <a-button @click="onRefresh" :disabled="loading">
                刷新
              </a-button>
            </a-space>
          </div>
        </a-form>
      </a-spin>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { getRTSPConfig, setRTSPConfig } from '@/api/rtsp'

// 响应式数据
const loading = ref(false)
const form = reactive({
  enabled: true,
  port: 554
})

// 计算属性
const deviceIP = computed(() => {
  return window.location.hostname || '192.168.1.100'
})

const liveURL = computed(() => {
  return `rtsp://${deviceIP.value}:${form.port}/live/1/0`
})

const recordURL = computed(() => {
  return `rtsp://${deviceIP.value}:${form.port}/record/1`
})

// 端口验证
const validatePort = async (rule, value) => {
  if (!value) {
    return Promise.reject('请输入端口号')
  }
  const port = Number(value)
  if (!Number.isInteger(port) || port < 1 || port > 65535) {
    return Promise.reject('端口号必须在1-65535之间')
  }
  return Promise.resolve()
}

// 加载配置
const loadConfig = async () => {
  loading.value = true
  try {
    console.log('开始加载RTSP配置...')
    const config = await getRTSPConfig()
    console.log('获取到的配置:', config)

    if (config && typeof config === 'object') {
      form.enabled = Boolean(config.enabled)
      form.port = Number(config.port) || 554
      console.log('配置已更新:', { enabled: form.enabled, port: form.port })
    } else {
      console.warn('配置格式异常:', config)
      message.warning('配置格式异常，使用默认值')
    }
  } catch (error) {
    console.error('加载RTSP配置失败:', error)
    message.error('加载配置失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 保存配置
const onSubmit = async () => {
  loading.value = true
  try {
    console.log('保存配置:', form)
    const config = {
      enabled: form.enabled,
      port: Number(form.port)
    }

    await setRTSPConfig(config)
    console.log('配置保存成功')
    message.success('RTSP配置保存成功')
  } catch (error) {
    console.error('保存RTSP配置失败:', error)
    message.error('保存失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 重置配置
const onReset = () => {
  form.enabled = true
  form.port = 554
  message.info('已重置为默认配置')
}

// 刷新配置
const onRefresh = () => {
  loadConfig()
}

// 组件挂载时加载配置
onMounted(() => {
  console.log('RTSPConfig组件已挂载，开始加载配置')
  loadConfig()
})
</script>

<style scoped>
.rtsp-config {
  width: 100%;
}

.status-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
}

.status-label {
  color: rgba(0, 0, 0, 0.65);
  font-size: 14px;
}

.help-text {
  color: rgba(0, 0, 0, 0.45);
  font-size: 12px;
  margin-top: 4px;
}

.url-examples {
  background: #fafafa;
  border-radius: 6px;
  padding: 16px;
  margin: 16px 0;
}

.url-examples h4 {
  margin: 0 0 8px 0;
  color: rgba(0, 0, 0, 0.85);
}

.description {
  color: rgba(0, 0, 0, 0.45);
  margin: 0 0 16px 0;
  font-size: 13px;
}

.url-display {
  margin: 0;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 13px;
  word-break: break-all;
}

.actions {
  margin-top: 24px;
  text-align: left;
}
</style>
